<template>
  <div style="display: flex; height: 100%; flex: 1; flex-direction: column">
    <TableSearchWidget ref="refSearch" :search="searchItems" style="margin: 24px 8px 16px 24px;">
      <template v-slot:searchHead>
        <slot name="searchHead"/>
      </template>
      <template v-slot:searchTail>
        <el-button icon="search" plain round style="padding: 0 20px;" @click="refresh"/>
      </template>
    </TableSearchWidget>

    <TableWidget ref="refHiDict" :pagination="pagination" :columns="columns" :load="loadData"
                 :has-select="false" :hide-pageable="false" style="flex: 1">
      <template v-slot:toolHeader>
        <el-button v-if="canAddDict()" type="primary" icon="Plus" @click="addDict" style="margin: 0 8px 0 8px;">
          新增字典值
        </el-button>
      </template>
      <template v-slot:actionBefore>
        <slot name="actionBefore"/>
      </template>
    </TableWidget>

    <EditDialog ref="refEditDlg" :columns="columns" :rules="rules" :submit="onSubmit"
                :form-label-width="100" :is-show-dialog="false"/>
  </div>
</template>

<script setup lang="ts">

import {onMounted, reactive, ref} from "vue";
import {msgError, msgInfo} from "@/utils/InfoUtil";
import EditDialog from "@/components/common/EditDialog.vue";
import {handleResult} from "@/utils/SystemUtil";
import {loadSystemDictValuePage, removeDictValue, saveDictValue} from "@/apis/sop";
import {useStore} from "@/stores";
import TableWidget from "@/widget/TableWidget.vue";
import TableSearchWidget from "@/widget/TableSearchWidget.vue";
import {hasMenuPermit} from "@/utils/sop/PermitUtil";

const props: any = withDefaults(defineProps<{
  dict?: any,
}>(), {});

const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

const store: any = useStore();
const refHiDict = ref();
const refSearch = ref();
const refEditDlg = ref();

const currentItem = ref();

const canAddDict = () => {
  return hasMenuPermit('asset:dict:add');
}

const canDeleteDict = () => {
  return hasMenuPermit('asset:dict:delete');
}

const canEditDict = () => {
  return hasMenuPermit('asset:dict:edit');
}

const searchItems = ref([
  {
    type: 'input',
    name: 'name',
    label: `字典名称`,
    size: 'default',
    placeholder: `请输入字典名`,
    clearable: true,
    defValue: '',
  },
  {
    type: 'input',
    name: 'value',
    label: `字典值`,
    size: 'default',
    placeholder: `请输入字典值`,
    clearable: true,
    defValue: '',
  }
]);

const rules = reactive({
  name: [{required: true, message: '请输入字典名', trigger: ['blur']},],
  value: [{required: true, message: '请输入字典值', trigger: ['blur']},],
})

const loadData = async (params: any) => {
  const currentPl: any = store.getCurrentPlatform();

  const result = await loadSystemDictValuePage({
    platformId: currentPl.id,
    dictId: props.dict.id,
    name: '',
    ...params
  });

  if (result && result.code === 0) {
    handleResult(result.data, ['$comment']);
  } else {
    msgError(result ? result.message : '加载字典值信息失败！');
  }

  return result;
}

const onSubmit = async (item: Record<string, any>, editType: string) => {
  item.existUpdate = 'add' == editType ? 0 : 1;
  const result = await saveDictValue(item);
  if (result && result.code === 0) {
    msgInfo('保存字典值信息成功!');
    setTimeout(() => refresh(), 300);
  } else {
    msgError(result ? result.message : '保存字典信息值失败！');
  }

  return result;
}

const newDictValue = () => {
  return {
    dictId: props.dict.id,
    platformId: props.dict.platformId
  };
}

const columns = ref([
  {
    id: 'id',
    name: '标识',
    hideCol: true,
    show: false,
    canEdit: false,
  },
  {
    id: 'name',
    name: '字典名',
    show: true,
  },
  {
    id: 'value',
    name: '字典值',
    show: true,
    inputCheck: (row: any) => {
      if (row.value.length > 1024) {
        row.value = row.value.substring(0, 1024);
      }
    }
  },
  {
    id: 'comment',
    name: '描述',
    show: true,
  },
  {
    id: 'createTime',
    name: '创建时间',
    show: false,
    canEdit: false,
  },
  {
    id: 'operation',
    name: '操作',
    show: true,
    hideCol: true,
    fixed: 'right',
    canEdit: false,
    operations: [
      {
        name: '编辑',
        iconType: 'primary',
        disabled: (row: any) => {
          return !canEditDict();
        },
        callback: (data: any, row: any) => {
          currentItem.value = row;
          refEditDlg.value?.editUpdate('编辑字典值', row);
        }
      },
      {
        type: 'confirm',
        name: '删除',
        disabled: (row: any) => {
          return !canDeleteDict();
        },
        confirm: async (data: any, row: any) => {
          row.state = 1;
          const result = await removeDictValue({
            dictId: row.dictId,
            dictName: row.name,
            platformId: row.platformId
          });
          if (result.code === 0) {
            msgInfo('删除字典值成功！');
            refresh();
          } else {
            msgError(result.message ? result.message : '删除字典值失败！');
          }
        }
      }
    ]
  }
]);

const addDict = () => {
  currentItem.value = newDictValue();
  refEditDlg.value?.editAdd('新增字典值', currentItem.value);
}

onMounted(() => {

})

const doRefresh = async (params: any) => {
  await refHiDict.value?.refreshData({
    ...params,
    ...refSearch.value?.getSearchParams()
  });
}

const refresh = () => {
  doRefresh({});
}

defineExpose({
  refresh,
})

</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}

</style>
